package com.xiaoma.tpo.webservice;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.xiaoma.tpo.dao.TimelineDao;
import com.xiaoma.tpo.domain.BonusClassAchievementRecord;
import com.xiaoma.tpo.domain.BonusClassAchievementResource;
import com.xiaoma.tpo.domain.ClsClass;
import com.xiaoma.tpo.domain.ClsCourse;
import com.xiaoma.tpo.domain.ClsCoursePrize;
import com.xiaoma.tpo.domain.ClsCourseVideo;
import com.xiaoma.tpo.domain.ClsGate;
import com.xiaoma.tpo.domain.ClsGateSentence;
import com.xiaoma.tpo.domain.ClsListeningQuestion;
import com.xiaoma.tpo.domain.ClsScore;
import com.xiaoma.tpo.domain.ClsSentence;
import com.xiaoma.tpo.domain.ClsUserClass;
import com.xiaoma.tpo.domain.ClsWord;
import com.xiaoma.tpo.domain.Timeline;
import com.xiaoma.tpo.domain.User;
import com.xiaoma.tpo.dto.ClsClassVo;
import com.xiaoma.tpo.dto.ClsCourseVo;
import com.xiaoma.tpo.dto.ClsGateScoreDto;
import com.xiaoma.tpo.dto.ClsScoreDto;
import com.xiaoma.tpo.resource.ClassAchievement;
import com.xiaoma.tpo.resource.TPOConstants;
import com.xiaoma.tpo.resource.TimelineContent;
import com.xiaoma.tpo.service.BonusPointService;
import com.xiaoma.tpo.service.ClassService;
import com.xiaoma.tpo.service.ImieLoginUserService;
import com.xiaoma.tpo.service.UserService;
import com.xiaoma.tpo.utils.Pager;
import com.xiaoma.tpo.utils.TPOUtils;
import com.xiaoma.verbal.dao.FctForecastDao;
import com.xiaoma.verbal.domain.FctForecast;

@Controller
@RequestMapping("/service/class")
public class ClassWs {
    
    private static Logger LOG = LoggerFactory.getLogger(ClassWs.class);
    
    @Autowired
    private ClassService classService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private ImieLoginUserService imieLoginUserService;
    
    @Autowired
    private BonusPointService bonusPointService;
    
    @Autowired
    private TimelineDao timelineDao;
    @Autowired
	private FctForecastDao fctForecastDao;
    
//    @RequestMapping(method = RequestMethod.GET)
//    @ResponseBody
//    public Map<String, Object> findAllClasses(){
//        List<ClsClassVo> classes = classService.findAllClasses();
//        Map<String, Object> result = new HashMap<String, Object>();
//        result.put("classes", classes);
//        return result;
//    }
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findAllClasses(String version){
    	Map<String, Object> result = new HashMap<String, Object>();
    	if("new".equals(version)){
    		List<ClsClassVo> classes = classService.findAllClasses();
    		List<ClsClassVo> willRemoveIds = new ArrayList<ClsClassVo>();
    		for(ClsClassVo clsClassVo : classes){
    			String type = clsClassVo.getType();
    			if("1".equals(type)){
    				String name = clsClassVo.getName();
    				String[] names = name.split(" ");
    				SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");
    				try {
    					Date date = sFormat.parse(names[0]);
    					Long time = System.currentTimeMillis();
    					Date date2 = new Date(time);
    					Date date3 = sFormat.parse(sFormat.format(date2));
    					if(date.getTime() < date3.getTime()){
    						willRemoveIds.add(clsClassVo);
    					}
    				} catch (ParseException e) {
    					continue;
    				}
    			}
    			
    		}
    		classes.removeAll(willRemoveIds);
    		willRemoveIds.clear();
    		result.put("classes", classes);
    	}else{
    		List<ClsClassVo> classes = classService.findAllClassesNoForecast();
    		result.put("classes", classes);
    	}
    	return result;
    }
    //只返回机经 其他的cls_class不返回
  @ResponseBody
  @RequestMapping(value="/finAllClassesOnlyForecast",method = RequestMethod.GET)
  public Map<String, Object> finAllClassesOnlyForecast(){
	  Map<String, Object> result = new HashMap<String, Object>();
      List<ClsClassVo> classesOnlyForecast = classService.finAllClassesOnlyForecast();
      List<ClsClassVo> willRemoveIds = new ArrayList<ClsClassVo>();
  	for(ClsClassVo clsClassVo : classesOnlyForecast){
  		String type = clsClassVo.getType();
  		if("1".equals(type)){
  			String name = clsClassVo.getName();
  			String[] names = name.split(" ");
  			SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");
  			try {
					Date date = sFormat.parse(names[0]);
					Long time = System.currentTimeMillis();
					Date date2 = new Date(time);
					Date date3 = sFormat.parse(sFormat.format(date2));
					if(date.getTime() < date3.getTime()){
						willRemoveIds.add(clsClassVo);
					}
				} catch (ParseException e) {
					continue;
				}
  		}
  		
  	}
  	classesOnlyForecast.removeAll(willRemoveIds);
  	willRemoveIds.clear();
  	result.put("classes", classesOnlyForecast);
    return result;
  }
    
    @RequestMapping(value = "/{classId}/courses" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findCoursesByClassId(@RequestHeader String token,@PathVariable Integer classId){
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;
            
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        //add class to user
//        ClsUserClass uc = classService.findUserClassByUserIdAndClassId(user.getId(), classId);
//        if (uc == null) {
//            uc = new ClsUserClass();
//            uc.setUserId(user.getId());
//            uc.setClsClassId(classId);
//            classService.saveUserClass(uc);
//        }
        
        List<ClsCourseVo> courses = classService.findCoursesByClassId(classId);
        result.put("courses", courses);
        userService.updateVisitTime(user);
        return result;
    }
    
    @RequestMapping(value = "/submitScores" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> submitScores(@RequestHeader String token, @RequestBody ClsScoreDto scoreDto){
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;
            
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        
        Integer classId = scoreDto.getClassId();
        List<ClsGateScoreDto> scoreDtos = scoreDto.getScores();
        Integer model = scoreDto.getModel();
        ClsClass clsClass = classService.findClassById(classId);
        if (clsClass == null) {
            result.put("status", 0);
            result.put("message", "can't find class with id " + classId);
            return result;
        }
        
        for (ClsGateScoreDto gateScore : scoreDtos) {
            ClsScore clsScore = classService.findScore(classId, gateScore.getCourseId(), gateScore.getGateId(),user.getId());
            if (clsScore == null) {
                clsScore = new ClsScore();
                clsScore.setClsClassId(classId);
                clsScore.setClsCourseId(gateScore.getCourseId());
                clsScore.setClsGateId(gateScore.getGateId());
                clsScore.setScore(gateScore.getScore());
                clsScore.setUserId(user.getId());
                classService.saveScore(clsScore);
            } else {
               if (clsScore.getScore() < gateScore.getScore()) {
                   clsScore.setScore(gateScore.getScore());
                   classService.updateScore(clsScore);
               }
            }
            
        }
        if (scoreDtos.size() > 0) {
            saveTimeline(user.getId(), TimelineContent.gate(scoreDtos.size()));
        }
        //计算奖杯，成就
        List<Integer> courseIds = classService.findPrizeCourse(classId, user.getId());
        for (Integer courseId: courseIds) {
            ClsCoursePrize coursePrize = classService.findCoursePrize(user.getId(), classId, courseId);
            if (coursePrize == null) {
                coursePrize = new ClsCoursePrize();
                coursePrize.setClsClassId(classId);
                coursePrize.setClsCourseId(courseId);
                coursePrize.setUserId(user.getId());
                classService.saveCoursePrize(coursePrize);
            }
        }
//        boolean finished = classService.finished(classId, user.getId());
//        if (finished) {//完成闯关，21*3 个gate 全部做完
//            saveAchievement(user, classId, ClassAchievement.FINISH.getPrize());
//        }
        if (courseIds.size() >= 7) {//获得7个奖杯
            saveAchievement(user, classId, ClassAchievement.COPPER.getPrize());
        }
        if (courseIds.size() >= 14) {//获得14个奖杯
            saveAchievement(user, classId, ClassAchievement.SILVER.getPrize());
        }
        if (courseIds.size() >= 21) {//获得21个奖杯
            saveAchievement(user, classId, ClassAchievement.GOLDEN.getPrize());
        }
        //end
        
        if (model == 1) {//返回结果集
            result.put("classId", classId);
            result.put("scores", classService.findScoresByClassIdAndUserId(classId, user.getId()));
            result.put("prizeCourseIds", courseIds);//获得奖杯的courseId
        } else {//不返回值
            result.put("status", 1);
            result.put("prizeCourseIds", courseIds);
        }
        
        userService.updateVisitTime(user);
        return result;
    }
    
    
//    @RequestMapping(value = "/gates/{gateId}" ,method = RequestMethod.GET)
//    @ResponseBody
//    public Map<String, Object> getGateById(@RequestHeader String token, @PathVariable Integer gateId){
//        Map<String, Object> result = new HashMap<String, Object>();
//        User user = userService.findByToken(token);
//        if(null == user) {
//            result.put("status", -2);
//            result.put("message", "invalid token");
//            return result;
//        }
//        if (TPOUtils.isAnonymous(user)) {
//            result.put("status", 0);
//            result.put("message", "anonymous can't access");
//            return result;
//            
//        }
//        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
//            result.put("status", -1);
//            result.put("message", "token disabled over 7 days, please login");
//            return result;
//        }
//        
//        ClsGate gate = classService.findGateById(gateId);
//        if (gate == null) {
//            result.put("status", 0);
//            result.put("message", "can't find gate with id " + gateId);
//        } else {
//            result.put("gate", gate);
//            if (Arrays.binarySearch(TPOConstants.SENTENCE_TB, gate.getType()) >= 0) {
//                result.put("records", classService.findSentencesByGateId(gateId));
//            } else {
//                result.put("records", classService.findWordsByGateId(gateId));
//            }
//        }
//        
//        userService.updateVisitTime(user);
//        return result;
//    }
    //因cls_sentence新添加了一个字段 dictation 修改上边的/gates/{gateId}接口
    @RequestMapping(value = "/gates/{gateId}" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getNewGateById(@RequestHeader String token, @PathVariable Integer gateId,String device){
    	Map<String, Object> result = new HashMap<String, Object>();
    	User user = userService.findByToken(token);
    	if(null == user) {
    		result.put("status", -2);
    		result.put("message", "invalid token");
    		return result;
    	}
    	if (TPOUtils.isAnonymous(user)) {
    		result.put("status", 0);
    		result.put("message", "anonymous can't access");
    		return result;
    		
    	}
    	if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
    		result.put("status", -1);
    		result.put("message", "token disabled over 7 days, please login");
    		return result;
    	}
    	
    	ClsGate gate = classService.findGateById(gateId);
    	if (gate == null) {
    		result.put("status", 0);
    		result.put("message", "can't find gate with id " + gateId);
    	} else {
    		result.put("gate", gate);
    		if (Arrays.binarySearch(TPOConstants.SENTENCE_TB, gate.getType()) >= 0) {
    			if("PC".equals(device)){
    				result.put("records", classService.findPCSentencesByGateId(gateId));
    			}else{
    				result.put("records", classService.findSentencesByGateId(gateId));
    			}
    		} else {
    			result.put("records", classService.findWordsByGateId(gateId));
    		}
    	}
    	
    	userService.updateVisitTime(user);
    	return result;
    }
    
    @RequestMapping(value = "/listening/{listeningId}/questions" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findListeningQuestions(@RequestHeader String token, @PathVariable Integer listeningId){
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;
            
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        
        List<ClsListeningQuestion> listeningQuestions = classService.findListeningQuestions(listeningId);
        result.put("listeningQuestions", listeningQuestions);
        userService.updateVisitTime(user);
        return result;
    }
    
    @RequestMapping(value = "/mine" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> findJoinedClass(@RequestHeader String token){
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;
            
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        
        List<ClsUserClass> userClasses = classService.findUserClassByUserId(user.getId());
        List<ClsClassVo> classes = classService.findAllClasses();
        //去掉过期的机经
        List<ClsClassVo> willRemoveIds = new ArrayList<ClsClassVo>();
    	for(ClsClassVo clsClassVo : classes){
    		String type = clsClassVo.getType();
    		if("1".equals(type)){
    			String name = clsClassVo.getName();
    			String[] names = name.split(" ");
    			SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd");
    			try {
					Date date = sFormat.parse(names[0]);
					Long time = System.currentTimeMillis();
					Date date2 = new Date(time);
					Date date3 = sFormat.parse(sFormat.format(date2));
					if(date.getTime() < date3.getTime()){
						willRemoveIds.add(clsClassVo);
					}
				} catch (ParseException e) {
					continue;
				}
    		}
    		
    	}
    	classes.removeAll(willRemoveIds);
    	willRemoveIds.clear();
        result.put("status", 1);
        result.put("userClasses", userClasses);
        result.put("classes", classes);
        
        userService.updateVisitTime(user);
        return result;
    }
    
    @RequestMapping(value = "/{classId}/join" ,method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> joinClass(@RequestHeader String token, @PathVariable Integer classId){
        Map<String, Object> result = new HashMap<String, Object>();
        User user = userService.findByToken(token);
        if(null == user) {
            result.put("status", -2);
            result.put("message", "invalid token");
            return result;
        }
        if (TPOUtils.isAnonymous(user)) {
            result.put("status", 0);
            result.put("message", "anonymous can't access");
            return result;
            
        }
        if (TPOUtils.over7days(new Date(), user.getLastVisit())) {//大于7天token失效
            result.put("status", -1);
            result.put("message", "token disabled over 7 days, please login");
            return result;
        }
        
        ClsUserClass uc = classService.findUserClassByUserIdAndClassId(user.getId(), classId);
        if (uc == null) {
            uc = new ClsUserClass();
            uc.setUserId(user.getId());
            uc.setClsClassId(classId);
            classService.saveUserClass(uc);
        }
        result.put("status", 1);
        userService.updateVisitTime(user);
        return result;
    }
    
    
    //------------以下为后台接口-----------------------

    /**
     * 21天class的列表
     * @return
     */
    @RequestMapping(value = "/sys/list" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getClassList(){
        Map<String, Object> result = new HashMap<String, Object>();

        List<ClsClass> list = classService.getClassList();
        result.put("rows", list);
        return result;
    }


    /**
     * 增加class
     * @param cvo
     * @return
     */
    @RequestMapping(value = "/sys/add" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addClass(@RequestParam MultipartFile file,ClsClassVo cvo){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.addClass(file,cvo);
        result.put("status", flag);
        return result;
    }


    @RequestMapping(value = "/sys/edit" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> editClass(@RequestParam MultipartFile file,ClsClassVo cvo){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.editClass(file,cvo);
        result.put("status", flag);
        return result;
    }


    @RequestMapping(value = "/sys/remove" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> removeClass(ClsClassVo cvo){
        Map<String, Object> result = new HashMap<String, Object>();
        if("1".equals(cvo.getType())){
        	result.put("status", "false");
        	return result;
        }
        boolean flag = false;
        flag = classService.removeClass(cvo);
        result.put("status", flag);
        return result;
    }
    //在21天中 判断 是不是机经 如果是则不可以编辑
    @RequestMapping(value = "/sys/judge" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> judgeClass(ClsClassVo cvo){
    	Map<String, Object> result = new HashMap<String, Object>();
    	if("1".equals(cvo.getType())){
    		result.put("status", "false");
    		return result;
    	}
    	result.put("status", true);
    	return result;
    }



    @RequestMapping(value = "/sys/courselist" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getCourseListByClass(Integer classId){
        Map<String, Object> result = new HashMap<String, Object>();
        List<ClsCourse> list = classService.getCourseByClassId(classId);
        result.put("rows",list);
        return result;
    }


    @RequestMapping(value = "/sys/add_course" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addCourse(ClsCourseVo cvo){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.addCourse(cvo);
        result.put("status", flag);
        return result;
    }


    @RequestMapping(value = "/sys/edit_course" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> editCourse(ClsCourseVo cvo){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.editCourse(cvo);
        result.put("status", flag);
        return result;
    }

    @RequestMapping(value = "/sys/remove_course" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> removeCourse(ClsCourseVo cvo){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.removeCourse(cvo);
        result.put("status", flag);
        return result;
    }


    @RequestMapping(value = "/sys/coursevideolist" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getCourseVideoList(Integer courseId){
        Map<String, Object> result = new HashMap<String, Object>();
        List<ClsCourseVideo> list = classService.getCourseVideo(courseId);
        result.put("rows",list);
        return result;
    }



    @RequestMapping(value = "/sys/add_course_video" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addCourseVideo(ClsCourseVideo cvo){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.addCourseVideo(cvo);
        result.put("status", flag);
        return result;
    }


    @RequestMapping(value = "/sys/edit_course_video" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> editCourseVideo(ClsCourseVideo cvo){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.editCourseVideo(cvo);
        result.put("status", flag);
        return result;
    }

    @RequestMapping(value = "/sys/remove_course_video" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> removeCourseVideo(ClsCourseVideo cvo){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.removeCourseVideo(cvo);
        result.put("status", flag);
        return result;
    }

    @RequestMapping(value = "/sys/gatelist" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getGateList(Integer courseId){
        Map<String, Object> result = new HashMap<String, Object>();
        List<ClsGate> list = classService.getGateList(courseId);
        result.put("rows",list);
        return result;
    }


    @RequestMapping(value = "/sys/add_gate" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addGate(ClsGate cvo){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.addGate(cvo);
        result.put("status", flag);
        return result;
    }


    @RequestMapping(value = "/sys/edit_gate" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> editGate(ClsGate cvo){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.editGate(cvo);
        result.put("status", flag);
        return result;
    }

    @RequestMapping(value = "/sys/remove_gate" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> removeGate(ClsGate cvo){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.removeGate(cvo);
        result.put("status", flag);
        return result;
    }


    @RequestMapping(value = "/sys/wordlist" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getWordList(Integer gateId){
        Map<String, Object> result = new HashMap<String, Object>();
        List<ClsWord> list = classService.getWordList(gateId);
        result.put("rows", list);
        return result;
    }


    @RequestMapping(value = "/sys/add_word" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addWord(ClsWord cw){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.addWord(cw);
        result.put("status", flag);
        return result;
    }


    @RequestMapping(value = "/sys/edit_word" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> editWord(ClsWord cw){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.editWord(cw);
        result.put("status", flag);
        return result;
    }

    @RequestMapping(value = "/sys/remove_word" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> removeWord(ClsWord cw){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.removeWord(cw);
        result.put("status", flag);
        return result;
    }


    @RequestMapping(value = "/sys/gateSentenceList" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getGateSentenceList(Integer gateId){
        Map<String, Object> result = new HashMap<String, Object>();
        List<ClsGateSentence> list = classService.getGateSentenceList(gateId);
        result.put("rows", list);
        return result;
    }


    @RequestMapping(value = "/sys/add_gate_sentence" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addGateSentence(ClsGateSentence cw){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.addGateSentence(cw);
        result.put("status", flag);
        return result;
    }


    @RequestMapping(value = "/sys/edit_gate_sentence" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> editGateSentence(ClsGateSentence cw){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.editGateSentence(cw);
        result.put("status", flag);
        return result;
    }

    @RequestMapping(value = "/sys/remove_gate_sentence" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> removeGateSentence(ClsGateSentence cw){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.removeGateSentence(cw);
        result.put("status", flag);
        return result;
    }
    @RequestMapping(value = "/sys/sentenceList" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getSentenceList(String sentence,String code,int page,int rows){
        Map<String, Object> result = new HashMap<String, Object>();
        Pager pager = classService.getSentenceList(sentence,code,page,rows);
        result.put("rows", pager.getList());
        result.put("total",pager.getTotalCount());
        return result;
    }



    @RequestMapping(value = "/sys/add_sentence" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> addSentence(ClsSentence cw){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.addSentence(cw);
        result.put("status", flag);
        return result;
    }


    @RequestMapping(value = "/sys/edit_sentence" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> editSentence(ClsSentence cw){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.editSentence(cw);
        result.put("status", flag);
        return result;
    }

    @RequestMapping(value = "/sys/remove_sentence" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> removeSentence(ClsSentence cw){
        Map<String, Object> result = new HashMap<String, Object>();
        boolean flag = false;
        flag = classService.removeSentence(cw);
        result.put("status", flag);
        return result;
    }
    //系统后台 查询User表
    @RequestMapping(value = "/sys/user" ,method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> findUsersByDay(@RequestParam String day,Integer page,Integer rows){
    	Map<String,Object> map = new HashMap<String, Object>();
    	Pager pager = userService.findAllUsersByDay(day,page,rows);
    	map.put("rows", pager.getList());
    	map.put("total", pager.getTotalCount());
    	return map;
    }
    //系统后台 查询IMIE 用户
    @RequestMapping(value = "/sys/imie" ,method = {RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public Map<String,Object> findImiesByDay(@RequestParam String day,Integer page,Integer rows){
    	Map<String,Object> map = new HashMap<String, Object>();
    	Pager pager = imieLoginUserService.findAllImiesByDay(day,page,rows);
    	map.put("rows", pager.getList());
    	map.put("total", pager.getTotalCount());
    	return map;
    }
    //判断要保存的机经是否存在
    @RequestMapping(value="/sys/judgeExist",method=RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> judgeExist(@RequestParam Integer fid,String  timeRange) {
    	Map<String, Object> result = new HashMap<String, Object>();
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	Date date=null;
    	try{
    		date = sdf.parse(timeRange);
    	}catch(Exception e){
    		e.printStackTrace();
    	}
    	FctForecast entity = new FctForecast();
    	entity.setTimeRange1(date);
    	List<FctForecast> rFctForecasts = fctForecastDao.findByColumns(entity);
		if(rFctForecasts.size() >0 && rFctForecasts !=null){
			//如果fid==null 就说明是保存
			if(fid == null){
				result.put("status",-1);
				result.put("message", "机经已存在");//此数据在前台不用，后台看着方便
				return result;
			//否则就是修改
			}else{
				FctForecast fctForecast = rFctForecasts.get(0);
				if(fid.equals(fctForecast.getId())){
					result.put("status",1);
					result.put("message", "机经不存在");//此数据在前台不用，看着方便
					return result;
				}else{
					result.put("status",-1);
					result.put("message", "机经已存在");//此数据在前台不用，后台看着方便
					return result;
				}
			}
		}
		result.put("status",1);
		result.put("message", "机经不存在");//此数据在前台不用，看着方便
		return result;
    }
    private void saveAchievement(User user, int classId, int achievement) {
        BonusClassAchievementRecord bonusClassAchievementRecord = bonusPointService.findAchievementBonusRecord(user.getId(), classId, achievement);
        if (bonusClassAchievementRecord == null) {
            bonusClassAchievementRecord = new BonusClassAchievementRecord();
            bonusClassAchievementRecord.setUserId(user.getId());
            bonusClassAchievementRecord.setClsClassId(classId);
            bonusClassAchievementRecord.setAchievement(achievement);
            bonusClassAchievementRecord.setBonusPoint(ClassAchievement.prize2Point(achievement));
            bonusClassAchievementRecord.setCreatedAt(new Date());
            BonusClassAchievementResource resource = bonusPointService.findAchievementResource(classId, achievement);
            if (resource != null) {
                bonusClassAchievementRecord.setResourceId(resource.getId());
            }
            bonusPointService.saveAchievementBonusRecord(bonusClassAchievementRecord);
            String title = resource == null ? null : resource.getTitle();
            saveTimeline(user.getId(), TimelineContent.achievement(title));
            
            user.setBonusPoint(user.getBonusPoint() + bonusClassAchievementRecord.getBonusPoint());
        }
    }
    
    private void saveTimeline(int userId, String content) {
        Timeline tl = new Timeline();
        tl.setContent(content);
        tl.setUserId(userId);
        tl.setCreatedAt(new Date());
        timelineDao.insert(tl);
    }
    

}
